let mongoose = require('../mongodb.js');
let ArticleModel = require("../model/articleModel.js");
import { text } from "../utils/utils";

/**
 * 写文章
 * @param option
 * @returns {*}
 */
function addArticle(option) {
	if(option.tag.length) {
		option.tag = option.tag.map(tagItem => new mongoose.Types.ObjectId(tagItem));
	}
	let article = new ArticleModel({
		title: option.title,
		description: text(option.description, 200),
		keyword: option.keyword,
		content: option.content,
		type: option.type,
		source: option.source,
		tag: option.tag,
		thumb: option.thumb
	});
	return article.save();
}

/**
 * 根据条件查询文章
 * @param tag
 * @param keyword
 * @param category
 * @param options
 * @returns {*}
 */
function findAllArticle({ tag = '', keyword, type }, options){
	let query = {};
	//标签查询
	if(tag !== '') {
		query = {
			tag: new mongoose.Types.ObjectId(tag)
		}
	}
	if(type !== '') {
		query = {
			type
		}
	}
	//关键字查询
	if(keyword !== '') {
		query = {
			$or : [
				{'title': {'$regex': keyword, $options: '$i'}},
				{'description': {'$regex': keyword, $options: '$i'}},
				{'content': {'$regex': keyword, $options: '$i'}}
			]
		}
	}
	return ArticleModel.paginate(query, options);
}

/**
 * 编辑文章
 * @param id
 * @param options
 * @returns {*}
 */
function updateArticleByOption({name, value}, options){
	return ArticleModel.findOneAndUpdate({
			[name]: value
	}, {$inc: {[options.type]: 1} });
}

module.exports = {
	addArticle,
	findAllArticle,
	updateArticleByOption
};
